#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import os
import codecs
#
#读取.properties文件中的android.library.reference信息,并将工程目录的绝对路径插入list中
#
#

class PropertiesReader(object):
	def __init__(self, fileName):
		self.fileName = fileName

	def getProperties(self):
		try:
			pro_file = codecs.open(self.fileName, 'r','utf-8')
			properties = {}
			for line in pro_file:
				if line.find('=') > 0:
					line = line.replace("\r\n","")
					line = line.replace("\\","/")
					strs = line.replace('\n', '').split('=')
					properties[strs[0]] = strs[1]
		except Exception as e:
			raise e
		else:
			pro_file.close()
			return properties

#递归获取所有依赖库工程的绝对路径
def recursionGetRefLibList(dirname,filename):
#	print("log,before recursionGetRefLibList check dir , dirname is",dirname)
	if( False == os.path.exists(dirname) ):
		raise Exception(dirname + "-目录不存在，请检查!")
		
	p = PropertiesReader(dirname + "/" + filename)
	properties = p.getProperties()

	rltlist = []
	for pro in properties:
		if(pro.startswith("android.library.reference")):
			propath = properties[pro]
			joinpath = os.path.join(dirname,propath)
			abspath = os.path.abspath(joinpath)
			rltlist.append(abspath)
#	print("log,rltlist is",rltlist)

	for lib in rltlist:
#		print("log,begin to reursionGet one reflib , reflib is",lib)
		rltlist += recursionGetRefLibList(lib,filename)

	return rltlist

#获取所有依赖库工程的目录并去重(这里的project.properties文件里的路径还必须都是相对路径，不然会报错！)
def getDupRemoveLibProject(basedirname,filename):
#	print("log,before getDupRemoveLibProject check dir , basedirname is",basedirname)
	reflib_dir_list = recursionGetRefLibList(basedirname,"project.properties")
	
	tempdict = {}
	for lib in reflib_dir_list:
		liblinuxpath = lib.replace("\\","/")
		tempdict[liblinuxpath] = liblinuxpath
	
	rltlist = []
	for lib in tempdict:
		rltlist.append(lib)

	return rltlist
	
if __name__=="__main__":
#	configlist = []
#	prodirname = "E:\SVN\SGSDK\SGAna\SGBAIDU\SGBAIDU_demo\project.properties"
#	pRd = PropertiesReader(prodirname)
#	configlist = pRd.getProperties()
#	for con in configlist:
#		print(con + "=" + configlist[con])
	
#递归获取的demo
	olddirname = "E:\SVN\CasualGames\popfarm_v6_four\proj.android"
	newdirname = "E:/gamecopy"
	temp = "E:/SVN/SGSDK/SGAna/SGMEIZU/SGMEIZU"
	basedirname = "E:/SVN/CasualGames/plugin/protocols/proj.android"

	reflib_dir_list = getDupRemoveLibProject(newdirname,"project.properties")
	for lib in reflib_dir_list:
		print(lib)


